/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NuevoProducto.java
 *
 * Created on 07-feb-2011, 22:25:52
 */
package es.nutroptima.soft;

import es.nutroptima.soft.model.Categoria;
import es.nutroptima.soft.model.MyVItem;
import es.nutroptima.soft.model.MyVTitulo;
import es.nutroptima.soft.model.Producto;
import es.nutroptima.soft.model.UnidadPeso;
import es.nutroptima.soft.model.factories.ItemsFactory;
import es.nutroptima.soft.submodels.CategoriasComboBoxModel;
import es.nutroptima.soft.submodels.MyVTitulosComboboxModel;
import es.nutroptima.soft.submodels.UnidadPesoComboBoxModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import nproductregister.NProductRegisterView;

/**
 *
 * @author Sergio Álvarez López <salvarez@nutroptima.es>
 */
public class NuevoProducto extends javax.swing.JPanel implements TableModelListener {

    private Bienvenida bienvenida;
    private NProductRegisterView view;
    private Producto producto;
    KeyListener numberListener = new KeyAdapter() {

        public void keyTyped(KeyEvent e) {
            char caracter = e.getKeyChar();
            if (((caracter < '0')
                    || (caracter > '9'))
                    && (caracter != KeyEvent.VK_BACK_SPACE)
                    && (caracter != '.')) {
                e.consume();
            }
        }
    };

    public NuevoProducto(NProductRegisterView aThis) {
        this.view = aThis;
        initComponents();
        this.listaCategorias.setModel(new CategoriasComboBoxModel("-- Seleccionar Categoría --"));
        this.tablaVyM.setDefaultEditor(UnidadPeso.class, new DefaultCellEditor(new JComboBox(new UnidadPesoComboBoxModel())));
        this.tablaVyM.setDefaultEditor(MyVTitulo.class, new DefaultCellEditor(new JComboBox(new MyVTitulosComboboxModel())));

        //Para validar números

        proteinas.addKeyListener(numberListener);
        hidratos.addKeyListener(numberListener);
        grasas.addKeyListener(numberListener);
        kCalorias.addKeyListener(numberListener);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelIems = new javax.swing.JPanel();
        myvLabel = new javax.swing.JLabel();
        addButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaVyM = new javax.swing.JTable();
        lMensajesEmergentes = new javax.swing.JLabel();
        jBorrarMicro = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        kcaloriasLabel = new javax.swing.JLabel();
        grasasLabel = new javax.swing.JLabel();
        hidratosLabel = new javax.swing.JLabel();
        proteinasLabel = new javax.swing.JLabel();
        proteinas = new javax.swing.JTextField();
        hidratos = new javax.swing.JTextField();
        grasas = new javax.swing.JTextField();
        kCalorias = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        listaCategorias = new javax.swing.JComboBox();
        nombre = new javax.swing.JTextField();
        categoriaLabel = new javax.swing.JLabel();
        nombreLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        cancel = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        infoLabel = new javax.swing.JLabel();
        macroErrorLabel = new javax.swing.JLabel();

        setEnabled(false);
        setName("Form"); // NOI18N
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(nproductregister.NProductRegisterApp.class).getContext().getResourceMap(NuevoProducto.class);
        panelIems.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("panelIems.border.title"))); // NOI18N
        panelIems.setName("panelIems"); // NOI18N

        myvLabel.setText(resourceMap.getString("myvLabel.text")); // NOI18N
        myvLabel.setName("myvLabel"); // NOI18N

        addButton.setText(resourceMap.getString("addButton.text")); // NOI18N
        addButton.setName("addButton"); // NOI18N
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tablaVyM.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaVyM.setName("tablaVyM"); // NOI18N
        tablaVyM.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                mvItemsModelKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(tablaVyM);

        lMensajesEmergentes.setText(resourceMap.getString("lMensajesEmergentes.text")); // NOI18N
        lMensajesEmergentes.setName("lMensajesEmergentes"); // NOI18N

        jBorrarMicro.setText(resourceMap.getString("jBorrarMicro.text")); // NOI18N
        jBorrarMicro.setName("jBorrarMicro"); // NOI18N
        jBorrarMicro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBorrarMicroActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout panelIemsLayout = new org.jdesktop.layout.GroupLayout(panelIems);
        panelIems.setLayout(panelIemsLayout);
        panelIemsLayout.setHorizontalGroup(
            panelIemsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, panelIemsLayout.createSequentialGroup()
                .addContainerGap(411, Short.MAX_VALUE)
                .add(lMensajesEmergentes, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 269, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(59, 59, 59))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, panelIemsLayout.createSequentialGroup()
                .add(20, 20, 20)
                .add(myvLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(addButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jBorrarMicro, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
                .add(298, 298, 298))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, panelIemsLayout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 699, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        panelIemsLayout.setVerticalGroup(
            panelIemsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelIemsLayout.createSequentialGroup()
                .add(panelIemsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(myvLabel)
                    .add(addButton)
                    .add(jBorrarMicro))
                .add(8, 8, 8)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 299, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(lMensajesEmergentes, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(panelIems, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 160, 740, 370));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        kcaloriasLabel.setText(resourceMap.getString("kcaloriasLabel.text")); // NOI18N
        kcaloriasLabel.setName("kcaloriasLabel"); // NOI18N

        grasasLabel.setText(resourceMap.getString("grasasLabel.text")); // NOI18N
        grasasLabel.setName("grasasLabel"); // NOI18N

        hidratosLabel.setText(resourceMap.getString("hidratosLabel.text")); // NOI18N
        hidratosLabel.setName("hidratosLabel"); // NOI18N

        proteinasLabel.setText(resourceMap.getString("proteinasLabel.text")); // NOI18N
        proteinasLabel.setName("proteinasLabel"); // NOI18N

        proteinas.setName("proteinas"); // NOI18N

        hidratos.setName("hidratos"); // NOI18N

        grasas.setName("grasas"); // NOI18N

        kCalorias.setName("kCalorias"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(proteinasLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(proteinas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(37, 37, 37)
                .add(hidratosLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(hidratos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(38, 38, 38)
                .add(grasasLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(grasas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(28, 28, 28)
                .add(kcaloriasLabel)
                .add(18, 18, 18)
                .add(kCalorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(49, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(proteinasLabel)
                    .add(proteinas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(hidratosLabel)
                    .add(hidratos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(kCalorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(kcaloriasLabel)
                    .add(grasas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(grasasLabel))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 80, 740, 70));

        jPanel2.setName("jPanel2"); // NOI18N

        listaCategorias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        listaCategorias.setName("listaCategorias"); // NOI18N

        nombre.setText(resourceMap.getString("nombre.text")); // NOI18N
        nombre.setName("nombre"); // NOI18N

        categoriaLabel.setText(resourceMap.getString("categoriaLabel.text")); // NOI18N
        categoriaLabel.setName("categoriaLabel"); // NOI18N

        nombreLabel.setText(resourceMap.getString("nombreLabel.text")); // NOI18N
        nombreLabel.setName("nombreLabel"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(13, 13, 13)
                .add(nombreLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(nombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 270, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(26, 26, 26)
                .add(categoriaLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(listaCategorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 300, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                        .add(categoriaLabel)
                        .add(listaCategorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(nombreLabel))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, nombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 740, 60));

        jPanel3.setName("jPanel3"); // NOI18N

        cancel.setText(resourceMap.getString("cancel.text")); // NOI18N
        cancel.setName("cancel"); // NOI18N
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        infoLabel.setBackground(resourceMap.getColor("infoLabel.background")); // NOI18N
        infoLabel.setForeground(resourceMap.getColor("infoLabel.foreground")); // NOI18N
        infoLabel.setText(resourceMap.getString("infoLabel.text")); // NOI18N
        infoLabel.setName("infoLabel"); // NOI18N

        macroErrorLabel.setBackground(resourceMap.getColor("macroErrorLabel.background")); // NOI18N
        macroErrorLabel.setForeground(resourceMap.getColor("macroErrorLabel.foreground")); // NOI18N
        macroErrorLabel.setText(resourceMap.getString("macroErrorLabel.text")); // NOI18N
        macroErrorLabel.setName("macroErrorLabel"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 98, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(saveButton)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(macroErrorLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 500, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(infoLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 500, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(cancel)
                    .add(saveButton)
                    .add(infoLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(1, 1, 1)
                .add(macroErrorLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 520, 730, 70));
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
        doSave();
    }

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        try {
            boolean pedienteSalvar = false;
            for (MyVItem myVItem : this.producto.getItems()) {
                pedienteSalvar = pedienteSalvar || myVItem.isActualizado();
            }
            if (pedienteSalvar) {
                int opcion = JOptionPane.showConfirmDialog(this, "Existe MICRONUTRIENTES sin guardar \n ¿Desea guardar los cambios en los micronutrientes?");
                if (opcion == JOptionPane.YES_OPTION) {
                    doSave();
                }
            }
            if (this.producto.isActualizado()) {
                int opcion = JOptionPane.showConfirmDialog(this, "Existe cambios en los MACRONUTRIENTES sin guardar \n ¿Desea guardar los cambios en los micronutrientes?");
                if (opcion == JOptionPane.YES_OPTION) {
                    doSave();
                }
            }
            view.getMainPanel().remove(this);
            view.getMainPanel().add(bienvenida, BorderLayout.NORTH);
            view.getMainPanel().updateUI();
            Logger.getLogger(this.getClass().getName()).info("Cambiando a vista de Bienvenida");
            this.bienvenida.reload();
            this.producto.removeTableModelListener(this);
        } catch (Exception ex) {
            Logger.getLogger(NuevoProducto.class.getName()).log(Level.SEVERE, null, ex);
            showError();
        }
}//GEN-LAST:event_cancelActionPerformed

    private void mvItemsModelKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mvItemsModelKeyTyped
    }//GEN-LAST:event_mvItemsModelKeyTyped

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        try {
            // TODO add your handling code here:
            MyVItem item = new MyVItem(producto);
            item.setTitulo(ItemsFactory.getInstance().getMyvTitulos().get(0));
            item.setUnidad(ItemsFactory.getInstance().getUnidadesPeso().get(0));
            this.producto.getItems().add(item);
            this.tablaVyM.updateUI();
        } catch (Exception ex) {
            Logger.getLogger(NuevoProducto.class.getName()).log(Level.SEVERE, null, "ERROR creando un nuevo item:" + ex);
            showError();
        }
    }//GEN-LAST:event_addButtonActionPerformed

    private void jBorrarMicroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBorrarMicroActionPerformed
        // TODO add your handling code here:
        int idx = tablaVyM.getSelectedRow();
        if (idx >= 0) {
            try {
                MyVItem item = producto.getItems().get(idx);
                int op = JOptionPane.showConfirmDialog(this, "¿Confirmar eliminación del micronutriente :" + item.getTitulo().getTitulo() + "?");
                if (op == JOptionPane.YES_OPTION) {
                    if (item.isAlrreadySave()) {
                        item.delete();
                    }
                    producto.getItems().remove(item);
                }

            } catch (Exception ex) {
                Logger.getLogger(NuevoProducto.class.getName()).log(Level.SEVERE, null, ex);
                showError();
            }
            this.tablaVyM.updateUI();
        } else {
            JOptionPane.showMessageDialog(this, "Debe seleccionar el micronutriente a borrar");

        }
    }//GEN-LAST:event_jBorrarMicroActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton cancel;
    private javax.swing.JLabel categoriaLabel;
    private javax.swing.JTextField grasas;
    private javax.swing.JLabel grasasLabel;
    private javax.swing.JTextField hidratos;
    private javax.swing.JLabel hidratosLabel;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JButton jBorrarMicro;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField kCalorias;
    private javax.swing.JLabel kcaloriasLabel;
    private javax.swing.JLabel lMensajesEmergentes;
    private javax.swing.JComboBox listaCategorias;
    private javax.swing.JLabel macroErrorLabel;
    private javax.swing.JLabel myvLabel;
    private javax.swing.JTextField nombre;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JPanel panelIems;
    private javax.swing.JTextField proteinas;
    private javax.swing.JLabel proteinasLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JTable tablaVyM;
    // End of variables declaration//GEN-END:variables

    private boolean checkFields() {
        boolean valido = true;
        double total = new Double((0.0));

        //El nombre no puede estar vacío
        if (nombre.getText().isEmpty()) {
            valido = false;
            nombreLabel.setForeground(Color.red);
            Logger.getLogger(this.getClass().getName()).info("Error validando nombre. Campo vacío");
        } else {
            nombreLabel.setForeground(Color.black);
        }

        //Hay se seleccionar una categoria
        if (listaCategorias.getSelectedIndex() == 0) {
            valido = false;
            categoriaLabel.setForeground(Color.red);
            Logger.getLogger(this.getClass().getName()).info("Error validando categorias. Ninguna categoría seleccionada");
        } else {
            categoriaLabel.setForeground(Color.black);
        }

        if (Double.parseDouble(kCalorias.getText()) < 1) {
            valido = false;
            kcaloriasLabel.setForeground(Color.red);
            Logger.getLogger(this.getClass().getName()).info("Error validando categorias. Ninguna categoría seleccionada");
        } else {
            kcaloriasLabel.setForeground(Color.black);
        }

        /*El porcentaje de macronutrientes debe ser 100%
        try{
        total = Double.parseDouble(proteinas.getText()) + Double.parseDouble(hidratos.getText()) + Double.parseDouble(grasas.getText());
        }
        catch(NumberFormatException n){
        macroErrorLabel.setText("Error en macronutrientes: Verifica los números");
        Logger.getLogger(this.getClass().getName()).info(n.toString());
        valido=false;
        return valido;
        }
        if(total!=100.0){
        valido=false;
        proteinasLabel.setForeground(Color.red);
        hidratosLabel.setForeground(Color.red);
        grasasLabel.setForeground(Color.red);
        macroErrorLabel.setText("El porcentaje total de macronutrientes debe ser 100% y es "+Double.toString(total)+"%");
        }else{
        proteinasLabel.setForeground(Color.black);
        hidratosLabel.setForeground(Color.black);
        grasasLabel.setForeground(Color.black);
        macroErrorLabel.setText("");
        }*/

        if (!valido) {
            infoLabel.setText("Por favor, verifica los campos marcados en rojo.");
        } else {
            infoLabel.setText("");
        }
        return valido;

    }

    public void setBienvenida(Bienvenida bienvenida) {
        this.bienvenida = bienvenida;
    }

    public void resetView(Producto p) {
        if (p != null) {
            this.nombre.setText(p.getTitulo());
            this.hidratos.setText("" + p.getHidratosCarbono());
            this.proteinas.setText("" + p.getProteinas());
            this.grasas.setText("" + p.getGrasas());
            this.kCalorias.setText("" + p.getKilocalorias());
            this.tablaVyM.setModel(p);
            this.panelIems.setVisible(true);
            p.addTableModelListener(this);
            ((CategoriasComboBoxModel) this.listaCategorias.getModel()).setSelectedItem(p.getCategoria());
            tablaVyM.setModel(p);
            saveButton.setText("Guardar cambios");
        } else {
            this.nombre.setText("");
            this.hidratos.setText("0");
            this.proteinas.setText("0");
            this.grasas.setText("0");
            this.kCalorias.setText("0");
            this.panelIems.setVisible(false);
        }
        this.producto = p;

    }

    public void showError() {
        JOptionPane.showMessageDialog(this, "Error salvando el micronutriente. Pongase en contacto con la central de Nutroptima");
    }

    public void doSave() {

        if (checkFields()) {
            try {
                //si el producto es nuevo lo construimos
                if (this.producto == null) {
                    this.producto = new Producto(this.bienvenida.getUsuarioconectado());
                    this.producto.addTableModelListener(this);
                }
                this.producto.setTitulo(this.nombre.getText());
                this.producto.setProteinas(Double.parseDouble(this.proteinas.getText()));
                this.producto.setGrasas(Double.parseDouble(this.grasas.getText()));
                this.producto.setHidratosCarbono(Double.parseDouble(this.hidratos.getText()));
                this.producto.setKilocalorias(Double.parseDouble(this.kCalorias.getText()));
                this.producto.setCategoria((Categoria) this.listaCategorias.getSelectedItem());
                this.producto.save();
                this.tablaVyM.setModel(producto);
                //Si muestra el panel de items y hay elementos en la tabla
                if (this.panelIems.isVisible() && tablaVyM.getRowCount() > 0) {
                    Logger.getLogger(this.getClass().getName()).info("Micronutrientes para salvar: " + tablaVyM.getRowCount());
                    for (int i = 0; i < tablaVyM.getRowCount(); i++) {
                        MyVItem item = this.producto.getItems().get(i);
                        item.save();
                        Logger.getLogger(this.getClass().getName()).info("Salvando el micronutriente: " + i);
                    }
                }
                //visualizar la tabla de las micronutrientes
                this.panelIems.setVisible(true);

            } catch (Exception ex) {
                Logger.getLogger(NuevoProducto.class.getName()).log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this, "Error al guardar la información.\n Por favor Llame a la central de Nutroptima. Gracias.");
            }
            Thread t = new Thread(new Runnable() {

                public void run() {
                    try {
                        infoLabel.setForeground(Color.black);
                        System.out.println("Durmiendo");
                        Thread.sleep(1500);
                        infoLabel.setText("");
                        System.out.println("Durmiendo");
                        Thread.sleep(100);
                        infoLabel.setText("Cambios guardados");
                        System.out.println("Durmiendo");
                        Thread.sleep(1500);
                        infoLabel.setText("");
                        System.out.println("Durmiendo");
                        Thread.sleep(100);
                        infoLabel.setText("Cambios guardados");
                        System.out.println("Durmiendo");
                        Thread.sleep(2500);
                        infoLabel.setText("");
                        infoLabel.setForeground(Color.red);
                        System.out.println("Despieto");
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Bienvenida.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            t.start();
        }
    }

    @Override
    public void tableChanged(TableModelEvent e) {
        this.tablaVyM.updateUI();
    }
}
